package 使用注解标记测试用例;

import java.lang.annotation.*;
import java.lang.reflect.*;

// 自定义测试注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Test {
    boolean enabled() default true;
}

// 测试类
class CalculatorTest {
    @Test
    public void testAdd() {
        Calculator calculator = new Calculator();
        assert calculator.add(2, 3) == 5 : "加法测试失败";
        System.out.println("testAdd 通过");
    }
    
    @Test(enabled = false)
    public void testDisabled() {
        System.out.println("这个测试不会执行");
    }
    
    @Test
    public void testSubtract() {
        Calculator calculator = new Calculator();
        assert calculator.subtract(5, 3) == 2 : "减法测试失败";
        System.out.println("testSubtract 通过");
    }
}

// 被测试的类
class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
    
    public int subtract(int a, int b) {
        return a - b;
    }
}

// 测试运行器
public class AnnotationDemo4 {
    public static void main(String[] args) throws Exception {
        System.out.println("开始运行测试...");
        
        CalculatorTest testObj = new CalculatorTest();
        Class<?> clazz = testObj.getClass();
        
        for (Method method : clazz.getMethods()) {
            if (method.isAnnotationPresent(Test.class)) {
                Test test = method.getAnnotation(Test.class);
                if (test.enabled()) {
                    try {
                        method.invoke(testObj);
                    } catch (Exception e) {
                        System.out.println(method.getName() + " 测试失败: " + e.getCause());
                    }
                } else {
                    System.out.println(method.getName() + " 测试被禁用");
                }
            }
        }
        
        System.out.println("测试运行结束");
    }
}